package com.example.vue_shop.utils;


import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * @author lipengwei
 */
public class TreeUtils {

    /**
     * 把 分页数据 转为 树形结构.
     * @param oneGradeDataMapList 分页数据
     * @param allDataMapList 所有数据
     * @param mainIdName 主键的名称（例如实体中是 id，则传入 id，是 shopId,就传入 shopId）
     * @param parentIdName 父级Id的名称 (实体中是 parentId 传 parentId, 是
     *                     shopTypeParentId 就传入 shopTypeParentId)
     * @return List<Map<String, Object>>
     */
    public static List<Map<String, Object>> getPageTree(
            List<Map<String, Object>> oneGradeDataMapList,
            List<Map<String, Object>> allDataMapList, String mainIdName,
            String parentIdName) {
        oneGradeDataMapList.forEach(map -> {
            int id = (int) map.get(mainIdName);
            List<Map<String, Object>> childrenList = (List<Map<String, Object>>) map.get("children");

            if (childrenList == null) {
                childrenList = new ArrayList<>();
            }
            for (Map<String, Object> rights : allDataMapList) {
                int parentId = (int) rights.get(parentIdName);
                if (id == parentId) {
                    childrenList.add(rights);
                    getPageTree(childrenList, allDataMapList, mainIdName, parentIdName);
                }
            }
            map.put("children", childrenList);
        });
        return oneGradeDataMapList;
    }
}
